<?php
class WDealEditHelper extends USystemWorklet
{
	public function taskAuthorize($id)
	{
		$deal = $id instanceOf MDeal ? $id : $this->deal($id);
		
		$locations = array();
		foreach($deal->locs as $loc)
			$locations[] = $loc->location;
		
		if($deal && (app()->user->checkAccess('administrator')
			|| (app()->user->checkAccess('citymanager')
				&& wm()->get('agent.citymanager.helper')->checkAccess($deal->id, $locations, 'deal'))
			|| ($deal->active == 0
				&& app()->user->checkAccess('company.edit',$deal->company,false))))
					return true;
		return false;
	}
	
	public function taskDeal($id)
	{
		static $deal;
		if(!isset($deal))
			$deal = MDeal::model()->findByPk($id);
		return $deal;
	}
	
	public function taskTranslations($model,$attribute,$purify=false)
	{
		// we need to save all fields translations
		$purifier = new CHtmlPurifier;
		$purifier->options = array(
			'Attr.AllowedFrameTargets' => array('_blank','_self','_parent','_top'),
			'HTML.SafeObject' => true,
			'HTML.SafeEmbed' => true,
			'Output.FlashCompat' => true,
		);
		
		foreach($model->$attribute as $lang=>$text)
			if($text)
			{
				if($purify)
					$text = $purifier->purify($text);
					
				$m = MDealI18N::model()->find('language=? AND dealId=? AND name=?',array(
					$lang,$model->id,$attribute
				));
				if(!$m)
				{
					$m = new MDealI18N;
					$m->dealId = $model->id;
					$m->language = $lang;
					$m->name = $attribute;
				}
				$m->value = $text;
				$m->save();
			}
	}
}